package com.dx.mes.service.brm.service;

import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_ADD;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_DELETE;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_NEW;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_QUERY;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_QUERY_BY_WO_ID;
import static com.dx.mes.common.bean.def.GenericDef.ACTION_FLG_UPDATE;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_OK;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_SET_ERROR;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.dx.mes.common.bean.def.GenericDef.RETURN_MESG_OK;
import static com.dx.mes.common.bean.def.GenericDef.TRX_OUT;
import static com.dx.mes.common.bean.def.GenericDef.E_FBPBISLAY_ADD_LAYOUT_ALREADY_EXIST;
import static com.dx.mes.common.bean.def.GenericDef.E_FBPBISLAY_NOT_FOUND_RECORD;
import static com.dx.mes.common.bean.def.GenericDef.E_FBPBISPTH_ITEM_ALREADY_EXIST;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dx.common.table.ppt.Bis_layot;
import com.dx.common.table.ppt.Bis_layot_gl;
import com.dx.common.table.ppt.Bis_layot_glId;
import com.dx.common.table.ppt.Bis_layot_lc;
import com.dx.common.table.ppt.Bis_layot_lcId;
import com.dx.common.table.ppt.Bis_mdl_def;
import com.dx.mes.common.dao.IBisLayotDao;
import com.dx.mes.common.dao.IBisLayotGLDao;
import com.dx.mes.common.dao.IBisLayotLCDao;
import com.dx.mes.common.dao.IBisMdlDefDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.brm.service.IFbpbislayoutService;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayI;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayIA;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayIB;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayIC;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayO;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayOA;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayOB;
import com.dx.mes.facade.brm.tx.Fbpbislay.FbpbislayOC;

@Service("fbpbislayoutService")
@SuppressWarnings({"unchecked"})
public class FbpbislayoutService implements IFbpbislayoutService {
	private static final String TX_NAME = "FBPBISLAY";
	private LogUtils logUtils;
	@Autowired
	private IBisLayotDao bisLayotDao;
	@Autowired
	private IBisLayotLCDao bisLayotLCDao;
	@Autowired
	private IBisLayotGLDao bisLayotGLDao;
//	@Autowired
//	private IRetWODao retWODao;
	@Autowired
	private IBisMdlDefDao bisMdlDefDao;
	
	public String subMainProc(String evt_no,String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FbpbislayoutService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FbpbislayoutService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		
		FbpbislayO outTrx = new FbpbislayO();

		outTrx.setTrx_id(TX_NAME);
		outTrx.setType_id(TRX_OUT);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		
		try {
			Session session = bisLayotDao.getCrSession();
			FbpbislayI inTrx = new FbpbislayI();

			inTrx = JacksonUtil.fromJson(strInMsg, FbpbislayI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_QUERY:
				queryByCondition(inTrx,outTrx);
				break;
			case ACTION_FLG_ADD:
				addORUpdateLocationFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_UPDATE:
				updateFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_DELETE:
				deleteFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_NEW:
				addORUpdateGroupFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_LIST_WHOLE:
				listWholeFnc(outTrx);
				break;
			case ACTION_FLG_QUERY_BY_WO_ID:
				queryByWOIDFnc(inTrx,outTrx);
				break;
			case 'C':
				addORUpdateLc(inTrx,outTrx);
				break;
			default:
				errActionFnc(outTrx);
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				session.flush();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}

		} catch (Exception ex) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			logUtils.info("[OutTrx:" + JacksonUtil.toJSONStr(outTrx) + "]");
		}
		return JacksonUtil.toJSONStr(outTrx);
	}

	public void addFnc(FbpbislayI inTrx,FbpbislayO outTrx) {
		FbpbislayIA iary = inTrx.getIary().get(0);
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if (bis_layot != null) {
			outTrx.setRtn_code(E_FBPBISLAY_ADD_LAYOUT_ALREADY_EXIST + "");
			outTrx.setRtn_mesg("bis_layot Already exist,Please Check");
			return;
		}
		Bis_layot bisLayot = new Bis_layot();
		bisLayot.setLayot_id(iary.getLayot_id());
		bisLayot.setLayot_dsc(iary.getLayot_dsc());
		bisLayot.setLayot_flg(inTrx.getAction_flg());
		bisLayot.setLayot_cate(iary.getLayot_cate());
		bisLayot.setX_axis_cnt(iary.getX_axis_cnt());
		bisLayot.setY_axis_cnt(iary.getY_axis_cnt());
		bisLayotDao.save(bisLayot);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void updateFnc(FbpbislayI inTrx,FbpbislayO outTrx) {
		FbpbislayIA iary = inTrx.getIary().get(0);
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if (bis_layot == null) {
			outTrx.setRtn_code(E_FBPBISLAY_NOT_FOUND_RECORD + "");
			outTrx.setRtn_mesg("bis_layot not found Record,Please Check");
			return;
		}
		bis_layot.setLayot_id(iary.getLayot_id());
		bis_layot.setLayot_dsc(iary.getLayot_dsc());
		bis_layot.setLayot_cate(iary.getLayot_cate());
		bis_layot.setX_axis_cnt(iary.getX_axis_cnt());
		bis_layot.setY_axis_cnt(iary.getY_axis_cnt());
		bisLayotDao.update(bis_layot);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void deleteFnc(FbpbislayI inTrx,FbpbislayO outTrx) {
		FbpbislayIA iary = inTrx.getIary().get(0);
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if (bis_layot == null) {
			outTrx.setRtn_code(E_FBPBISLAY_NOT_FOUND_RECORD + "");
			outTrx.setRtn_mesg("bis_layot not found Record,Please Check");
			return;

		}
		if (bis_layot.getLayot_cate() == "G") {
			String hql = "FROM Bis_layot_gl where id.layotg_id_fk='" + layot_id + "'";
			List<Bis_layot_gl> bisLayotGList = bisLayotGLDao.find(hql);
			if (bisLayotGList.size() > 0) {
				for (Bis_layot_gl bis_layot_gl : bisLayotGList) {
					bisLayotGLDao.delete(bis_layot_gl);
				}
			}
		}
		bisLayotDao.delete(bis_layot);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryByCondition(FbpbislayI inTrx,FbpbislayO outTrx ) {
		FbpbislayIA iary = inTrx.getIary().get(0);
		String hql = " FROM Bis_layot where 1=1 ";
		String layot_id = iary.getLayot_id();
		String layot_flg = iary.getLayot_flg();
		if (layot_id != null) {
			if(layot_id.indexOf('*') == -1){
				hql = hql + " and id.layot_id = '" + layot_id + "'";
			}else{
				hql = hql + " and id.layot_id like '"+ layot_id.replace('*', '%')+"'";
			}
		}
		if (layot_flg != null) {
			hql = hql + " and layot_flg ='" + layot_flg + "'";
		}
		List<FbpbislayOA> oaryList = new ArrayList<FbpbislayOA>();
		List<Bis_layot> layotList = bisLayotDao.find(hql);
		for (Bis_layot bis_layot : layotList) {
			FbpbislayOA oary = new FbpbislayOA();
			oary.setLayot_id(bis_layot.getLayot_id());
			oary.setLayot_flg(bis_layot.getLayot_flg());
			oary.setLayot_dsc(bis_layot.getLayot_dsc());
			oary.setLayot_cate(bis_layot.getLayot_cate());
			oary.setX_axis_cnt(bis_layot.getX_axis_cnt());
			oary.setY_axis_cnt(bis_layot.getY_axis_cnt());
			if (("G").equals(bis_layot.getLayot_flg()) && layotList.size() == 1) {
				String hql2 = "FROM Bis_layot_gl where id.layotg_id_fk='" + bis_layot.getLayot_id() + "'";
				List<Bis_layot_gl> bisLayotGLList = bisLayotGLDao.find(hql2);
				List<FbpbislayOB> oaryBList = new ArrayList<FbpbislayOB>();
				for (Bis_layot_gl bis_layot_gl : bisLayotGLList) {
					FbpbislayOB oaryB = new FbpbislayOB();
					Bis_layot bis_layot_2 = bisLayotDao.get(bis_layot_gl.getId().getLayot_id_fk());
					oaryB.setLayotg_id_fk(bis_layot_gl.getId().getLayotg_id_fk());
					oaryB.setLayot_id_fk(bis_layot_gl.getId().getLayot_id_fk());
					oaryB.setX_axis(bis_layot_gl.getId().getX_axis());
					oaryB.setY_axis(bis_layot_gl.getId().getY_axis());
					oaryB.setMrr_loc(bis_layot_gl.getMrr_loc());
					oaryB.setPos_id(bis_layot_gl.getPos_id());
					oaryB.setLayot_dsc(bis_layot_2.getLayot_dsc());
					oaryBList.add(oaryB);
				}
				if (bisLayotGLList.size() > 0) {
					oary.setOaryB(oaryBList);
					oary.setTbl_cnt_b(oaryBList.size());
				}
			} else if (layotList.size() == 1) {
				String hql3 = "FROM Bis_layot_lc where id.layot_id_fk='" + bis_layot.getLayot_id() + "'";
				List<Bis_layot_lc> bisLayotLCList = bisLayotLCDao.find(hql3);
				List<FbpbislayOC> oaryCList = new ArrayList<FbpbislayOC>();
				for (Bis_layot_lc bis_layot_lc : bisLayotLCList) {
					FbpbislayOC oaryC = new FbpbislayOC();
					oaryC.setLayot_id_fk(bis_layot_lc.getId().getLayot_id_fk());
					oaryC.setX_axis(bis_layot_lc.getId().getX_axis());
					oaryC.setY_axis(bis_layot_lc.getId().getY_axis());
					oaryC.setPos_id(bis_layot_lc.getPos_id());
					oaryC.setMrr_loc(bis_layot_lc.getMrr_loc());
					oaryC.setPos_dsc(bis_layot_lc.getPos_dsc());
					oaryCList.add(oaryC);
				}
				if (bisLayotLCList.size() > 0) {
					oary.setOaryC(oaryCList);
					oary.setTbl_cnt_c(oaryCList.size());
				}
			}
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);

	}

	public void listWholeFnc(FbpbislayO outTrx) {
		List<FbpbislayOA> oaryList = new ArrayList<FbpbislayOA>();

		List<Bis_layot> bisLayotList = bisLayotDao.loadAll();
		for (Bis_layot bis_layot : bisLayotList) {
			FbpbislayOA oary = new FbpbislayOA();
			oary.setLayot_id(bis_layot.getLayot_id());
			oary.setLayot_dsc(bis_layot.getLayot_dsc());
			oary.setX_axis_cnt(bis_layot.getX_axis_cnt());
			oary.setY_axis_cnt(bis_layot.getY_axis_cnt());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void addORUpdateLocationFnc(FbpbislayI inTrx,FbpbislayO outTrx) {

		FbpbislayIA iary = inTrx.getIary().get(0);
		// 如果bis_layot ,则新增一笔
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
//		if (bis_layot == null) {
			addFnc(inTrx,outTrx);
//		} else {
////			updateFnc(inTrx,outTrx);
//			
//		}
	}

	public void addORUpdateLc(FbpbislayI inTrx,FbpbislayO outTrx){
		List<FbpbislayIA> iary = inTrx.getIary();
		for (FbpbislayIA iaryA : iary) {
			Bis_layot_lcId lcId = getBisLayotLc(iaryA);
			Bis_layot_lc bis_layot_lc = bisLayotLCDao.get(lcId);
			if (bis_layot_lc == null) {
				addLcFnc(iaryA,inTrx,outTrx);
			}else {
				updateLcFnc(iaryA,inTrx,outTrx);
			}
			
		}
		
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	private Bis_layot_lcId getBisLayotLc(FbpbislayIA iaryA) {
		String layot_id_fk = iaryA.getLayot_id_fk();
		String x_axis = iaryA.getX_axis();    
		String y_axis = iaryA.getY_axis();   
		Bis_layot_lcId lcId = new Bis_layot_lcId();
		lcId.setLayot_id_fk(layot_id_fk);
		lcId.setX_axis(x_axis);
		lcId.setY_axis(y_axis);
		return lcId;
	}
	
	private void updateLcFnc(FbpbislayIA iaryA, FbpbislayI inTrx,FbpbislayO outTrx) {
		Bis_layot_lcId lcId = getBisLayotLc(iaryA);
		Bis_layot_lc bis_layot_lc = bisLayotLCDao.get(lcId);
		setValueLc(iaryA, bis_layot_lc,inTrx);
		bisLayotLCDao.saveOrUpdate(bis_layot_lc);
		
	}

	private void addLcFnc(FbpbislayIA iaryA,FbpbislayI inTrx, FbpbislayO outTrx) {
		Bis_layot_lcId lcId = getBisLayotLc(iaryA);
		Bis_layot_lc bis_layot_lc  = new Bis_layot_lc();
		bis_layot_lc.setId(lcId);
		setValueLc(iaryA, bis_layot_lc,inTrx);
		bisLayotLCDao.save(bis_layot_lc);
	}

	private void setValueLc(FbpbislayIA iaryA, Bis_layot_lc bis_layot_lc,FbpbislayI inTrx) {
		bis_layot_lc.setMrr_loc(iaryA.getMrr_loc());
		bis_layot_lc.setPos_id(iaryA.getPos_id());
		bis_layot_lc.setEvt_usr(inTrx.getEvt_usr());
		bis_layot_lc.setEvt_timestamp(Util.getCurrentTimestamp());
	}

	public void addORUpdateGroupFnc(FbpbislayI inTrx,FbpbislayO outTrx) {
		FbpbislayIA iary = inTrx.getIary().get(0);
		List<FbpbislayIB> iaryBList = iary.getIaryB();
		// 如果Bis_layot表中没有记录 则新增一笔
		String layot_id = iary.getLayot_id();
		Bis_layot bis_layot = bisLayotDao.get(layot_id);
		if (bis_layot == null) {
			addFnc(inTrx,outTrx);
		} else {
			updateFnc(inTrx,outTrx);
		}
		// 删除Bis_layot_gl下 layout_group所有记录
		String hql = "FROM Bis_layot_gl where id.layotg_id_fk='" + layot_id + "'";
		List<Bis_layot_gl> bisLayotGLList = bisLayotGLDao.find(hql);
		for (Bis_layot_gl bis_layot_gl : bisLayotGLList) {
			bisLayotGLDao.delete(bis_layot_gl);
		}
		for (FbpbislayIB iaryB : iaryBList) {
			Bis_layot_gl bis_layot_gl = new Bis_layot_gl();
			Bis_layot_glId id = new Bis_layot_glId();
			id.setLayotg_id_fk(iaryB.getLayotg_id_fk());
			id.setLayot_id_fk(iaryB.getLayot_id_fk());// TODO:是否需要查询Bis_layot表确认是否存在
														// //不需要
			id.setX_axis(iaryB.getX_axis());
			id.setY_axis(iaryB.getY_axis());
			bis_layot_gl.setId(id);
			bis_layot_gl.setMrr_loc(iaryB.getMrr_loc());
			bis_layot_gl.setPos_id(iaryB.getPos_id());
			bisLayotGLDao.save(bis_layot_gl);
		}
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryByWOIDFnc(FbpbislayI inTrx,FbpbislayO outTrx) {
//		FbpbislayIA iary = inTrx.getIary().get(0);
//		Ret_wo ret_wo = retWODao.get(iary.getWo_id());
//		if (ret_wo == null) {
//			outTrx.setRtn_code(E_XPLAYOUT_NOT_FOUND_WO + "");
//			outTrx.setRtn_mesg("Not found Record[wo_id:" + iary.getWo_id() + "] in RET_WO");
//			return;
//		}
//		if ("Y".equals(inTrx.getBind_so_flg())) {
//			if (ret_wo.getMdl_id_fk() == null) {
//				outTrx.setRtn_code(E_XPLAYOUT_NOT_BIND_SO + "");
//				outTrx.setRtn_mesg("此内部订单［" + iary.getWo_id() + "］ 没有绑定商务订单，请去5200完成绑定！");
//				return;
//			}
//
//		}
//		Bis_mdl_def bis_mdl_def = bisMdlDefDao.get(ret_wo.getMdl_id_fk());
//		if (bis_mdl_def == null) {
//			outTrx.setRtn_code(E_XPLAYOUT_NOT_FOUND_MDL_ID + "");
//			outTrx.setRtn_mesg("Not found Record[mdl_id_fk:" + ret_wo.getMdl_id_fk() + "] in BIS_MDL_DEF");
//			return;
//		}
//
//		String dqr_flg = (bis_mdl_def.getRsv_info() != null && bis_mdl_def.getRsv_info().charAt(1) == 'Y') ? "Y" : "N";
//		if (dqr_flg == "Y") {
//			outTrx.setRtn_code(E_XPLAYOUT_DQR_MDL_ID + "");
//			outTrx.setRtn_mesg("内部订单：[" + iary.getWo_id() + "]的产品型号[" + ret_wo.getMdl_id_fk() + "]版式为["
//					+ bis_mdl_def.getLayot_id_fk() + "]，请确定是否正确，如不正确请修正!");
//			return;
//		}
//		inTrx.getIary().get(0).setLayot_id(bis_mdl_def.getLayot_id_fk());
//		queryByCondition(inTrx,outTrx);
//
	}

	public void errActionFnc(FbpbislayO outTrx) {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}

}
